import React, { useState } from 'react';
import style from './index.module.css';
import { InboxOutlined } from '@ant-design/icons';
import { useDispatch } from 'react-redux';
import { Button, message, Upload } from 'antd';
import { UploadRequest } from "@/utils/request.js";
import { toggleUploadFlag } from '@/redux/home/scientificResearchManagementSystem';
const { Dragger } = Upload;
export default function UploadCard() {

  const [fileList, setFileList] = useState([]);
  const [uploading, setUploading] = useState(false);
  const dispatch = useDispatch();


  const handleCancel = () => {
    dispatch(toggleUploadFlag());
  };


  const props = {
    onRemove: (file) => {
      const index = fileList.indexOf(file);
      const newFileList = fileList.slice();
      newFileList.splice(index, 1);
      setFileList(newFileList);
    },
    beforeUpload: (file) => {
      setFileList([...fileList, file]);
      return false;
    },
    fileList,
  };


  async function handleUpload() {
    const formData = new FormData();
    fileList.forEach((file) => {
      formData.append('file', file);
    });
    setUploading(true);
    // You can use any AJAX library you like
    await UploadRequest('scientificResearchManagementSystem/upload', formData)
    setUploading(false);
    setFileList([]);
    message.success('上传成功');
  };

  return (
    <div className={style.Container}>
      <div className={style.firstRow}>
        <div className={style.left}>
          <div>下载模板:</div>
          <div className={style.download}>点击下载</div>
        </div>
      
        <Button onClick={handleCancel}>关闭</Button>
      </div>
      <div className={style.draggerContainer}>
        <Dragger {...props} >
          <p className="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p className="ant-upload-text">拖拽文件至此,点击上传</p>
          <p className="ant-upload-hint">
            Support for a single or bulk upload. Strictly prohibited from uploading company data or other
            banned files.
          </p>
        </Dragger>
      </div>
      <div className={style.uploadButton}>
        <Button
          className={style.upload}
          type="primary"
          onClick={handleUpload}
          disabled={fileList.length === 0}
          loading={uploading}
          style={{
            marginTop: 16,
          }}
        >
          {uploading ? '上传中' : '上传'}
        </Button>
      </div>



    </div >
  )
}
